package com.cyru.statemachine.core.impl;

import com.cyru.statemachine.core.State;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * description:
 *
 * @author zhangxuchuan
 * date 2022/5/2
 */
public class States<S, E, C> {

    private final Map<S, State<S, E, C>> stateMap = new ConcurrentHashMap<>();

    public State<S, E, C> addState(State<S, E, C> state) {
        stateMap.put(state.getId(), state);
        return state;
    }

    public State<S, E, C> getState(S source) {
        return stateMap.get(source);
    }

    public List<State<S, E, C>> getStates() {
        return new ArrayList<>(stateMap.values());
    }

    public State<S, E, C> getStateOrDefault(S id) {
        State<S, E, C> state = getState(id);
        if (state == null) {
            return addState(new DefaultState<>(id));
        }
        return state;
    }


}
